<!--
 * @Description:
 * @Autor: huHaiBo
 * @Date: 2022-03-10 09:15:45
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-10-24 16:39:36
-->
<template>
  <div>
    <el-dialog :title="option.title" :visible.sync="option.visible" :width="option.width">
      <el-upload
        ref="upload"
        class="upload-demo"
        action="https://jsonplaceholder.typicode.com/posts/"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :file-list="fileList"
        :auto-upload="false"
        :on-change="handleChange"
      >
        <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
        <el-button v-if="!option.templateBtn" slot="trigger" size="small" type="primary" :loading="isSubmitLoadingTemp ? true : false" @click="downLoadTemp">下载模板</el-button>
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" :loading="isSubmitLoading ? true : false" @click="submitUpload">上传到服务器</el-button>
      </el-upload>

    </el-dialog>
  </div>
</template>

<script>
import uploadRequest from '@/utils/uploadRequest'
export default {
  props: {
    option: {
      type: Object,
      default: () => {
        return { title: '' }
      }
    }
  },
  data() {
    return {
      fileList: [],
      mode: {},
      isSubmitLoadingTemp: false,
      isSubmitLoading: false
    }
  },
  methods: {
    async  submitUpload() {
      try {
        this.isSubmitLoading = true
        const fd = new FormData()
        this.fileList.map(item => {
          fd.append(item.name, item.raw)
        })
        if (this.option.query) {
          for (const k in this.option.query) {
            fd.append(k, this.option.query[k])
          }
        }
        this.fileList = []
        const data = await uploadRequest.post(this.option.uploadUrl, fd)
        this.$emit('submitUpload', data)
      } catch (err) {
        console.log('🚀 ~ file: uploadDialog.vue ~ line 70 ~ submitUpload ~ err', err)
      } finally {
        this.option.visible = false
        this.isSubmitLoading = false
      }
    },
    handleRemove(file, fileList) {

    },
    handlePreview(file) {

    },
    handleChange(file, fileList) {
      this.fileList = fileList
    },
    downLoadTemp() {
      this.isSubmitLoadingTemp = true
      window.location.href = this.option.templateUrl
      console.log('🚀 ~ file: uploadDialog.vue:85 ~ downLoadTemp ~ this.option.templateUrl:', this.option.templateUrl)
      setTimeout(() => {
        this.isSubmitLoadingTemp = false
      }, 500)
    }
  }
}
</script>
